const Koa = require('koa')
const app = new Koa();
const path = require('path')
const fs = require('fs')
const axios = require('axios')
const static = require('koa-static')
const bodyParser = require('koa-bodyparser')
const staticPath = path.join(__dirname, './build')
const targetServer = 'http://baojia.chelun.com'

app.use(static(staticPath))
app.use(bodyParser())

app.use(async function (ctx, next) {
  if (ctx.get('x-request-http')) {//axios请求
    let options = {
      url: targetServer + ctx.request.url,
      method: ctx.request.method
    }
    if (options.method === 'GET') {//get请求方式
      options.params = ctx.request.query
    } else {//post请求方式
      options.data = ctx.request.body
    }
    try {
      const res = await axios(options)
      ctx.body = res.data
    } catch (error) {
      ctx.statusCode = 500;
      ctx.body = error
    }
    // finally{
    //     // 这个东西无论成功或失败最终都会执行 可以不用写
    //     console.log('最终执行')
    // }
  } else {
    await next()
  }
})

app.use(async function (ctx) {
  ctx.body = fs.readFileSync(path.join(staticPath, 'index.html'), 'utf8')
})

app.listen(3000, () => {
  console.log('port is 3000')
})